package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.web.domain.dto.DifyRequestDto;
import org.dromara.web.domain.dto.DifyResponseDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;


import java.time.Duration;

@Validated
@RestController
@SaIgnore
@RequiredArgsConstructor
@RequestMapping("/dify")
@Slf4j
public class DifyController {



    // Dify API 配置
    @Value("${dify.api.url}")
    private String difyApiUrl;

    @Value("${dify.api.key}")
    private String difyApiKey;

    // WebClient 配置
    private final WebClient webClient = WebClient.builder()
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(10 * 1024 * 1024)) // 10MB
        .build();

    @GetMapping("/getUserId")
    public Integer getUserId() {
        // 直接获取当前登录用户ID
        Long userId = getCurrentUserId();
        if (userId != null) {
            log.info("获取到当前登录用户ID：{}", userId);
            return userId.intValue();
        }
        log.warn("用户未登录，无法获取用户ID");
        return null;
    }

    // 简化的用户ID获取方法
    private Long getCurrentUserId() {
        try {
            LoginUser loginUser = getLoginUser();
            if (ObjectUtil.isNotNull(loginUser)) {
                return loginUser.getUserId();
            }
        } catch (Exception e) {
            log.error("获取当前用户ID失败", e);
        }
        return null;
    }



    /**
     * 调用 Dify API 进行对话
     *
     * @param request Dify 请求参数
     * @return Dify API 响应结果
     */
    @PostMapping("/chat")
    public R<DifyResponseDto> chatWithDify(@RequestBody DifyRequestDto request) {
        try {
            log.info("开始调用 Dify API，请求参数：{}", request);

            // 验证API配置
            if (difyApiUrl == null || difyApiUrl.trim().isEmpty()) {
                log.error("Dify API URL 未配置");
                return R.fail("Dify API URL 未配置，请检查配置文件");
            }

            if (difyApiKey == null || difyApiKey.trim().isEmpty()) {
                log.error("Dify API Key 未配置");
                return R.fail("Dify API Key 未配置，请检查配置文件");
            }

            // 验证请求参数
            if (request.getQuery() == null || request.getQuery().trim().isEmpty()) {
                log.error("查询内容不能为空");
                return R.fail("查询内容不能为空");
            }

            Long currentUserId = getCurrentUserId();

            // 设置用户ID（从当前登录用户获取）
            if (currentUserId != null) {
                request.setUser(String.valueOf(currentUserId));
                log.info("使用当前登录用户ID：{}", currentUserId);
            } else {
                log.warn("用户未登录，使用默认用户标识");
                request.setUser("default-user");
            }

            // 设置默认响应模式
            if (request.getResponseMode() == null || request.getResponseMode().trim().isEmpty()) {
                request.setResponseMode("blocking");
                log.debug("设置默认响应模式为 blocking");
            }

            log.info("准备调用 Dify API，URL：{}，用户：{}", difyApiUrl, request.getUser());

            // 调用 Dify API
            DifyResponseDto response = webClient.post()
                .uri(difyApiUrl)
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + difyApiKey)
                .bodyValue(request)
                .retrieve()
                .bodyToMono(DifyResponseDto.class)
                .timeout(Duration.ofSeconds(30))
                .block();

            if (response != null) {
                log.info("Dify API 调用成功，会话ID：{}，消息ID：{}",
                    response.getConversationId(), response.getMessageId());
                return R.ok("调用成功", response);
            } else {
                log.error("Dify API 返回空响应");
                return R.fail("Dify API 返回空响应");
            }

        } catch (Exception e) {
            String errorMsg = "调用 Dify API 失败";
            if (e.getMessage() != null) {
                if (e.getMessage().contains("timeout")) {
                    errorMsg = "调用 Dify API 超时，请稍后重试";
                } else if (e.getMessage().contains("401")) {
                    errorMsg = "Dify API 认证失败，请检查API Key";
                } else if (e.getMessage().contains("404")) {
                    errorMsg = "Dify API 地址不存在，请检查配置";
                }
            }
            log.error("{}，异常详情：", errorMsg, e);
            return R.fail(errorMsg + "：" + e.getMessage());
        }
    }

    /**
     * 简单的文本对话接口
     *
     * @param query 查询文本
     * @return Dify API 响应结果
     */
    @PostMapping("/simple-chat")
    public R<DifyResponseDto> simpleChatWithDify(@RequestParam String query) {
        try {
            Long currentUserId = getCurrentUserId();
            // 构建简单的请求对象
            DifyRequestDto request = DifyRequestDto.builder()
                .query(query)
                .responseMode("blocking")
                .conversationId("")
                .userId(String.valueOf(currentUserId))
                .build();

            return chatWithDify(request);

        } catch (Exception e) {
            log.error("简单对话调用失败", e);
            return R.fail("简单对话调用失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 当前登录用户的信息，如果用户未登录则返回 null
     */
    private LoginUser getLoginUser() {
        LoginUser loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser;
    }


/*
curl -X POST 'http://localhost/v1/chat-messages' \
--header 'Authorization: Bearer {api_key}' \
--header 'Content-Type: application/json' \
--data-raw '{
  "inputs": {},
  "query": "What are the specs of the iPhone 13 Pro Max?",
  "response_mode": "streaming",
  "conversation_id": "",
  "user": "abc-123",
  "files": [
      {
          "type": "image",
          "transfer_method": "remote_url",
          "url": "https://cloud.dify.ai/logo/logo-site.png"
      }
  ]
}'
 */


}
